package com.tanhua.server.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.dubbo.server.pojo.RecommendUser;
import com.tanhua.dubbo.server.vo.PageInfo;

import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.RecommendUserQueryParam;
import com.tanhua.server.vo.TodayBest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

@Service
public class TodayBestService {
    @Autowired
    private UserService userService;

    @Autowired
    private RecommendUserService recommendUserService;

    @Value("${tanhua.sso.default.user}")
    private Long defaultUser;

    @Autowired
    private UserInfoService userInfoService;

    /**
     * 查询今日佳人
     * @param token
     * @return
     */
    public TodayBest queryTodayBest(String token) {
        //校验token是否有效，通过sso的接口进行校验
        User user=userService.queryUserByToken(token);
        //防止收到user为空，代码严谨性吧
        if(null==user){
            return null;
        }
        TodayBest todayBest=recommendUserService.queryTodayBest(user.getId());
        //检测佳人是否存在（新用户可能不存在对应的佳人）
        if(null==todayBest){
            //给出默认的推荐用户
            todayBest=new TodayBest();
            todayBest.setId(defaultUser);
            todayBest.setFateValue(90L);//固定缘分值
        }
        //根据userid去userinfo表中查询相关信息
        UserInfo userInfo=userInfoService.queryUserInfoByUserId(todayBest.getId());
        //判断得到的userInfo是否为空
        if(null==userInfo){
            return null;
        }
        //为todayBest补全信息
        /**
         * Long id;
         * String avatar;
         * String nickname;
         * String gender; //性别 man woman
         * Integer age;
         * String[] tags;
         * Long fateValue; //缘分值
         */
        todayBest.setAvatar(userInfo.getLogo());
        todayBest.setNickname(userInfo.getNickName());
        todayBest.setGender(userInfo.getSex().getValue()==1?"man":"woman");
        todayBest.setAge(userInfo.getAge());
        todayBest.setTags(StringUtils.split(userInfo.getTags(),","));
        return todayBest;
    }

    /**
     * 查询推荐用户列表
     * @param token
     * @param queryParam
     * @return
     */
    public PageResult queryRecommendation(String token, RecommendUserQueryParam queryParam) {
        //利用dubbo的RPC调用sso系统进行校验token,并返回User对象，在tanhua-server服务器中有该方法，可直接调用
        User user=userService.queryUserByToken(token);
        //判断得到的user是否为空
        if(null==user){
            return null;
        }
        //创建PageResult对象
        PageResult pageResult=new PageResult();
        //设置PageResult（后台返回去定义的对象）已经可以设置的参数,根据RecommendUserQueryParam对象设置的（从前台传过来）
        pageResult.setPage(queryParam.getPage());
        pageResult.setPagesize(queryParam.getPagesize());

        //使用PageInfo去接收MongoDB查询出来的RecommendUser集合、当前页面数，和页面大小,
        //当然传递的参数可以由User以及RecommendUserQueryParam提供
        PageInfo<RecommendUser> pageInfo=recommendUserService.queryRecommendUserList(user.getId(),
                                                                                    queryParam.getPage(),
                                                                                    queryParam.getPagesize());
        //得到PageInfo对象中封装RecommendUser对象的集合List<T> records
        List<RecommendUser> records=pageInfo.getRecords();
        if(CollectionUtils.isEmpty(records)){
            //没有查询到推荐的用户列表
            return pageResult;
        }

        //用set集合收集推荐用户的id,防止重复
        Set<Long> userIds=new HashSet<>();
        //遍历records集合，获取userId
        for (RecommendUser record : records) {
            userIds.add(record.getUserId());
        }

        //构建查询条件构造器
        QueryWrapper<UserInfo> queryWrapper=new QueryWrapper<>();

        //用户id参考
        queryWrapper.in("user_id",userIds);

        if(StringUtils.isNotEmpty(queryParam.getGender())){
            //需要性别参数查询
            //queryWrapper.eq("sex",StringUtils.equals(queryParam.getGender(),"man")?1:2);//方便测试，注释掉
        }

        if (StringUtils.isNotEmpty(queryParam.getCity())){
            //需要城市参数查询
            //queryWrapper.like("city",queryParam.getCity());//方便测试，注释掉
        }

        if (queryParam.getAge()!=null){
            //设置年龄参数
            //queryWrapper.le("age",queryParam.getAge());//方便测试，注释掉
        }

        //根据符合条件的userIds里面的集合去userInfo查询用户信息，并用list集合封装
        List<UserInfo> userInfoList=userInfoService.queryUserInfoList(queryWrapper);
        if(CollectionUtils.isEmpty(userInfoList)){
            //没有查询到用户的信息
            return pageResult;
        }

        //TodayBest对象的集合封装接下来需要定义的PageResult对象
        List<TodayBest> todayBests=new ArrayList<>();
        //遍历userInfoList,设置相关信息
        for (UserInfo userInfo : userInfoList) {
            TodayBest todayBest=new TodayBest();

            todayBest.setId(userInfo.getUserId());
            todayBest.setAvatar(userInfo.getLogo());
            todayBest.setNickname(userInfo.getNickName());
            todayBest.setTags(StringUtils.split(userInfo.getTags(),','));
            todayBest.setGender(userInfo.getSex().getValue()==1?"man":"woman");
            todayBest.setAge(userInfo.getAge());
            //设置缘分值
            for (RecommendUser record : records) {
                if(record.getUserId().longValue()==userInfo.getUserId().longValue()){
                    double score = Math.floor(record.getScore());//向下取整
                    todayBest.setFateValue(Double.valueOf(score).longValue());
                    break;
                }
            }
            todayBests.add(todayBest);
        }
        //按照缘分值进行倒序排序
        Collections.sort(todayBests,(o1, o2) -> new Long(o2.getFateValue()-o1.getFateValue()).intValue());
        //将todayBests添加进pageResult对象
        pageResult.setItems(todayBests);

        return pageResult;
    }
}
